#include <string.h>
#include <time.h>
#include <egg/Egg2.h>

struct
{
	char* name;
	echar* value;
}hQuery;

hQuery hItems[] = {
	{"url", ""},	   //0,新闻url
	{"title", ""},		//1,新闻标题
	{"website", ""},	//2,域名
	{"content", ""},	//3,正文内容
	{"date", ""},		//4,发布日期,格式：2011-06-16
	{"datetime", ""},	//5,发布精确时间,格式：2011-06-16 06:09:34
	{"insert_datetime", ""},	//6,插入精确时间,格式:2011-06-16 06:09:34
	{"category", "财经"},	//7,类别,eg:财经
};

static void set_time()
{
	char buf[10];
	time_t rawtime;
	struct tm *timeinfo;

	time(&rawtime);
	timeinfo = localtime(&rawtime);
	sprintf(buf, "%4d-%02d-%02d", 1900+timeinfo->tm_year, 1+timeinfo->tm_mon, timeinfo->tm_mday);

	hItems[4].value = buf;
}

static void set_all_field(HEGGDOCUMENT hDocument)
{
	if(EGGDOCUMENT_IS_INVALID(hDocument))
	{
		return ;
	}

	int i;
	for(i = 0; i < 7; i++)
	{
		HEGGFIELD hField = eggDocument_get_field(hDocument, hItems[i].name);

		unsigned len = 0;
		echar* val = eggField_get_value(hField, &len);
		hItems[i].value = val;

		free(val);
		hField = 0;
	}
}

//get bas
int main()
{
	set_time();

	HEGGHTTP hHttp = eggHttp_open("");

	HEGGINDEXREADER hIndexReader = eggIndexReader_open(hHttp);
	HEGGINDEXSEARCHER hIndexSearcher = eggIndexSearcher_new(hIndexReader);

	HEGGQUERY hCategory = eggQuery_new_string(hItems[7].name, hItems[7].value, strlen(hItems[7].value), EGG_NULL);
	HEGGQUERY hTime = eggQuery_new_string(hItems[4].name, hItems[4].value, strlen(hItems[4].value), EGG_NULL);

	eggQuery_and(hCategory, hTime);
	eggQuery_delete(hTime);

	HEGGTOPCOLLECTOR hTopCollector = eggTopCollector_new(0);
	int ret = eggIndexSearcher_search_with_query(hIndexSearcher, hTopCollector, hCategory);
	if(ret == EGG_TRUE)
	{
		eggTopCollector_normalized(hTopCollector, EGG_TOPSORT_SCORE);

		HEGGSCOREDOC lp_score_doc = eggTopCollector_top_docs(hTopCollector);
		count_t cnt = eggTopCollector_total_hits(hTopCollector);

		while(cnt--)
		{
			HEGGDOCUMENT lp_doc = EGG_NULL;
			eggIndexReader_get_document(hIndexReader, lp_score_doc[cnt].idDoc, &lp_doc);

			set_all_field(lp_doc);

			eggDocument_delete(lp_doc);
		}
	}
	
	return 0;
}
